package com.sunxueqi.project.system.service.impl;

import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sunxueqi.common.constant.StatusConstants;
import com.sunxueqi.common.utils.KeyGenerate;
import com.sunxueqi.common.utils.SecurityUtils;
import com.sunxueqi.project.system.dao.RoleMapper;
import com.sunxueqi.project.system.dao.RoleMenuMapper;
import com.sunxueqi.project.system.service.IRoleService;
import com.sunxueqi.project.system.vo.Role;
import com.sunxueqi.project.system.vo.RoleMenu;
import com.sunxueqi.project.system.vo.User;

@Service
public class RoleServiceImpl implements IRoleService{
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private RoleMenuMapper roleMenuMapper;
	
	public List<String> getRolesByUser(User user){
		List<String> roles = new LinkedList<String>();
		if(user.isAdmin()) {
			// admin角色拥有所有权限
			roles.add("admin");
		} else {
			roles.addAll(roleMapper.selectRolesByUserId(user.getId()));
		}
		return roles;
	}

	@Override
	public List<Role> selectRoleList(Role role) {
		role.setDeleteStatus(StatusConstants.NORMAL);
		return roleMapper.selectList(role);
	}

	@Override
	public int addRole(Role role) {
		role.setId(KeyGenerate.getKeyId());
		role.setDeleteStatus(StatusConstants.NORMAL);
		role.setCreateBy(SecurityUtils.getLoginUserId());
		role.setCreateTime(new Timestamp(System.currentTimeMillis()));
		roleMapper.insert(role);
		return insertRoleMenu(role);
	}

	@Override
	public int updateRole(Role role) {
		role.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		role.setUpdateBy(SecurityUtils.getLoginUserId());
		int count = roleMapper.updateByPrimaryKey(role);
		return count;
	}

	@Override
	public int deleteRoleByIds(String[] idArray) {
		int result = 0;
		for(String id: idArray) {
			Role role = new Role();
			role.setId(id);
			role.setDeleteStatus(StatusConstants.DELETED);
			role.setDeleteTime(new Timestamp(System.currentTimeMillis()));
			role.setDeleteBy(SecurityUtils.getLoginUserId());
			int count = roleMapper.updateByPrimaryKey(role);
			result += count;
		}
		return result;
	}

	@Override
	public int changeStatus(Role role) {
		return roleMapper.updateByPrimaryKey(role);
	}
	
	/**
	 * 新增角色与菜单的关系
	 * @param role
	 * @return
	 */
	public int insertRoleMenu(Role role) {
		int rows = 0;
		List<RoleMenu> list = new LinkedList<RoleMenu>();
		for(String menuId: role.getMenuIds()) {
			RoleMenu rm = new RoleMenu();
			rm.setId(KeyGenerate.getKeyId());
			rm.setRoleId(role.getId());
			rm.setMenuId(menuId);
			list.add(rm);
		}
		if(!list.isEmpty()) {
			rows = roleMenuMapper.addRoleMenu(list);
		}
		return rows;
	}
}
